﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using BomberManServer.Utils;

namespace BomberManServer.Flashs
{
    class Flash
    {
        Thread thread;
        TcpListener server;
        LinkedList<TcpClient> clients;
        MemoryStream crossdomain;

        public Flash()
        {
            // load the file
            crossdomain = new MemoryStream();

            StreamWriter sw = new StreamWriter(crossdomain);
            sw.WriteLine("<?xml version=\"1.0\"?><!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\"><!-- Policy file for xmlsocket://socks.mysite.com --><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"5000-5025\" /></cross-domain-policy>\0");
            sw.Flush();

            // create server on port 843
            server = new TcpListener(System.Net.IPAddress.Any,843);
            server.Server.Blocking = false;
            clients = new LinkedList<TcpClient>();

            // create thread
            thread = new Thread(new ThreadStart(run));
            thread.Start();
        }

        private void run()
        {
            // listen on port 843
            server.Start();

            while(true) {

                while(server.Pending())
                    clients.AddLast(server.AcceptTcpClient());

                foreach (TcpClient client in clients)
                {
                    // there is a message
                    if (client.ReceiveBufferSize > 0)
                        // lets parse it
                        client.Client.Blocking = true;

                        onData(client.GetStream());
                }

                // add something that clean the clients

                Thread.Sleep(0);
            }
        }

        private void onData(NetworkStream stream)
        {
            byte[] buffer = new byte[1024];
            stream.Read(buffer,0,1024);
            String s = Encoding.UTF8.GetString(buffer);

            // wait for <policy-file-request/>
            if(!s.Contains("<policy-file-request/>")) return;

            // send crossdomain.xml
            crossdomain.WriteTo(stream);
        }
    }
}
